package server

import (
	"encoding/json"
	"net/http"
	"net/url"
	"open-platform/cache"
	"open-platform/env"
	"open-platform/jsonstruct"
	"strings"
)

// 发起授权
func authorization(w http.ResponseWriter, r *http.Request) {

	componentAppId := r.URL.Query().Get("component_appid")
	authType := r.URL.Query().Get("auth_type")

	if "" == componentAppId {
		response(w, "参数错误", "400")
		return
	}

	if "" == authType {
		authType = "1"
	}

	component, err := cache.GetComponent(componentAppId)

	if nil != err {
		response(w, err.Error(), "500")
		return
	}

	preAuthCodeJson, err := component.OpenPlatform.CreatePreAuthorizationCode()

	if nil != err {
		response(w, err.Error(), "500")
		return
	}

	var preAuthCode map[string]interface{}
	err = json.Unmarshal(preAuthCodeJson, &preAuthCode)

	if nil != err {
		response(w, "解析json失败！", "500")
		return
	}

	redirectUri := env.EnvConfig.AuthorizedCallback
	redirectUri += "?component_app_id=" + componentAppId + "&auth_type=" + authType
	redirectUri = url.QueryEscape(redirectUri)

	urlParam := map[string]string{
		"component_appid": component.AppId,
		"pre_auth_code":   preAuthCode["pre_auth_code"].(string),
		"redirect_uri":    redirectUri,
		"auth_type":       authType,
	}

	param := makeUrlParam(urlParam)

	var authorizationUrl = env.EnvConfig.WechatDomain + "/cgi-bin/componentloginpage?" + param

	body := `

		跳转中，请稍后

		<script>
			setTimeout(function(){
				window.location.href = "{AUTHORIZATION_URL}"
			}, 0);
		</script>
	`

	body = strings.Replace(body, "{AUTHORIZATION_URL}", authorizationUrl, 1)

	w.Header().Add("Content-Type", "text/html;charset=utf-8")

	response(w, body, "200")

}

//授权完成过后的页面
func authorized(w http.ResponseWriter, r *http.Request) {

	authCode := r.URL.Query().Get("auth_code")
	componentAppId := r.URL.Query().Get("component_app_id")
	authType := r.URL.Query().Get("auth_type")

	if "" == authCode || "" == componentAppId || "" == authType {
		response(w, "参数错误！", "400")
		return
	}

	var authTypeInt int = 1

	if "2" == authType {
		authTypeInt = 2
	}

	component, err := cache.GetComponent(componentAppId)

	if nil != err {
		response(w, err.Error(), "500")
		return
	}

	result, err := component.OpenPlatform.HandleAuthorize(authCode)

	if nil != err {
		response(w, err.Error(), "500")
		return
	}

	authorization := jsonstruct.Authorization{}

	err = json.Unmarshal(result, &authorization)

	if nil != err {
		response(w, "解析数据失败："+string(result), "500")
		return
	}

	authorizationInfo := authorization.AuthorizationInfo

	_, err = cache.MakeOfficialAccount(
		authorizationInfo,
		component.AppId,
		authTypeInt,
	)

	if nil != err {
		response(w, err.Error(), "500")
		return
	}

	var callbackUrl string = component.CallbackUrl

	callbackUrl = strings.Replace(
		callbackUrl,
		"APPID",
		authorizationInfo.AppId,
		1,
	)

	http.Redirect(w, r, callbackUrl, 301)

}
